package com.endurance.gateway.filter.factory;

 import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
 import org.springframework.util.ObjectUtils;
 import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

 import java.util.Collections;
 import java.util.List;

/**
 * 自定义认证的filter
 */
// 注意 在工厂中创建这个对象
@Component
//@Configuration  而不是配置
public class TokenGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenGatewayFilterFactory.Config> {

    /**
     * 构造方法
     */
    public TokenGatewayFilterFactory() {
        super(Config.class);
    }

    // 明确设定Config的参数值是什么
    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("requiredToken");
    }

    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            /**
             * 参数1：webflux新的web模型 springmvc 传统web模型：HttpServletRequest HttpServletResponse
             * 参数2：GatewayFilterChain
             * @param exchange
             * @param chain
             * @return
             */
            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                String token = exchange.getRequest().getQueryParams().get("token").get(0);
                System.out.println("获取的token信息：" + token);
                // 2. redis中获取token信息
                    if (ObjectUtils.isEmpty(token)) {
                        throw new RuntimeException("无效令牌");
                    }
                boolean requiredToken = config.isRequiredToken();
                System.out.println("当前获取Config中的数据：" + requiredToken);
                // 放行到后端微服务继续处理
                return chain.filter(exchange);
            }
        };
    }

    /**
     * 静态类
     */
    public static class Config {
        private boolean requiredToken;

        public boolean isRequiredToken() {
            return requiredToken;
        }

        public void setRequiredToken(boolean requiredToken) {
            this.requiredToken = requiredToken;
        }
    }

}
